home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / ohlutil.zip / TAIL.C < prev    next >
C/C++ Source or Header  |  1990-05-31  |  21KB  |  821 lines

  1. /* tail -- output last part of file(s)
  2.    Copyright (C) 1989, 1990 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Can display any amount of data, unlike the Unix version, which uses
  19.    a fixed size buffer and therefore can only deliver a limited number
  20.    of lines.
  21.  
  22.    Started by Paul Rubin <phr@ai.mit.edu>
  23.    Finished by David MacKenzie <djm@ai.mit.edu>
  24.  
  25.    Usage: tail [-n [+]#] [-lbcfqv] [+number [+]#] [+lines] [+blocks]
  26.           [+chars] [+follow] [+quiet] [+silent] [+verbose] [file...]
  27.  
  28.           tail [+/-#lbcfqv] [file...]
  29.  
  30.    Options:
  31.    -n, +number [+]#    Number of items to tail (default 10).
  32.             If the number starts with a `+', begin printing with
  33.             the #th item from the start of each file, instead of
  34.             from the end.
  35.    -l, +lines        Tail by lines (the default).
  36.    -b, +blocks        Tail by 512-byte blocks.
  37.    -c, +chars        Tail by characters.
  38.    -f, +follow        Loop forever trying to read more characters at the
  39.             end of the file, on the assumption that the file
  40.             is growing.  Ignored if reading from a pipe.
  41.             Cannot be used if more than one file is given.
  42.    -q, +quiet, +silent    Never print filename headers.
  43.    -v, +verbose        Always print filename headers.
  44.  
  45.    Reads from standard input if no files are given or when a filename of
  46.    ``-'' is encountered.
  47.    By default, filename headers are printed only more than one file
  48.    is given.  */
  49.  
  50. #include <stdio.h>
  51. #include <ctype.h>
  52. #include <sys/types.h>
  53. #include "getopt.h"
  54. #include "system.h"
  55.  
  56. #ifdef STDC_HEADERS
  57. #include <errno.h>
  58. #include <stdlib.h>
  59. #define ISDIGIT(c) (isdigit ((unsigned char) (c)))
  60. #else
  61. #define ISDIGIT(c) (isascii (c) && isdigit (c))
  62. char *malloc ();
  63. void free ();
  64.  
  65. extern int errno;
  66. #endif
  67.  
  68. #ifndef _POSIX_SOURCE
  69. long lseek();
  70. #endif
  71.  
  72. /* Number of items to tail. */
  73. #define DEFAULT_NUMBER 10
  74.  
  75. /* The number of bytes in a block (-b option). */
  76. #define BLOCKSIZE 512
  77.  
  78. /* Size of atomic reads. */
  79. #define BUFSIZE (BLOCKSIZE * 8)
  80.  
  81. /* Masks for the operation mode.  If neither CHARS nor BLOCKS is set,
  82.    tail operates by lines. */
  83. #define CHARS 1            /* Tail by characters. */
  84. #define BLOCKS 2        /* Tail by blocks. */
  85. #define FOREVER 4        /* Read from end of file forever. */
  86. #define START 8            /* Count from start of file instead of end. */
  87. #define HEADERS 16        /* Print filename headers. */
  88.  
  89. /* When to print the filename banners. */
  90. enum header_mode
  91. {
  92.   multiple_files, always, never
  93. };
  94.  
  95. char *xmalloc ();
  96. int file_lines ();
  97. int pipe_chars ();
  98. int pipe_lines ();
  99. int start_chars ();
  100. int start_lines ();
  101. int tail ();
  102. int tail_chars ();
  103. int tail_file ();
  104. int tail_lines ();
  105. long atou();
  106. void dump_remainder ();
  107. void error ();
  108. void usage ();
  109. void write_header ();
  110. void xwrite ();
  111.  
  112. extern int errno;
  113.  
  114. /* The name this program was run with. */
  115. char *program_name;
  116.  
  117. struct option long_options[] =
  118. {
  119.   {"number", 1, NULL, 'n'},
  120.   {"lines", 0, NULL, 'l'},
  121.   {"blocks", 0, NULL, 'b'},
  122.   {"chars", 0, NULL, 'c'},
  123.   {"follow", 0, NULL, 'f'},
  124.   {"quiet", 0, NULL, 'q'},
  125.   {"silent", 0, NULL, 'q'},
  126.   {"verbose", 0, NULL, 'v'},
  127.   {NULL, 0, NULL, 0}
  128. };
  129.  
  130. void
  131. main (argc, argv)
  132.      int argc;
  133.      char **argv;
  134. {
  135.   enum header_mode header_mode = multiple_files;
  136.   int errors = 0;        /* Exit status. */
  137.   int mode = 0;            /* Flags. */
  138.   /* In START mode, the number of items to skip before printing; otherwise,
  139.      the number of items at the end of the file to print.  Initially, -1
  140.      means the value has not been set. */
  141.   long number = -1;
  142.   int c;            /* Option character. */
  143.   int longind;            /* Index in `long_options' of option found. */
  144.  
  145.   program_name = argv[0];
  146.  
  147.   if (argc > 1
  148.       && ((argv[1][0] == '-' && ISDIGIT (argv[1][1]))
  149.       || (argv[1][0] == '+' && (ISDIGIT (argv[1][1]) || argv[1][1] == 0))))
  150.     {
  151.       /* Old option syntax: a dash or plus, one or more digits, and one or
  152.      more option letters. */
  153.       if (argv[1][0] == '+')
  154.     mode |= START;
  155.       if (ISDIGIT (argv[1][1]))
  156.     {
  157.       for (number = 0, ++argv[1]; ISDIGIT (*argv[1]); ++argv[1])
  158.         number = number * 10 + *argv[1] - '0';
  159.       /* Parse any appended option letters with getopt. */
  160.       if (*argv[1])
  161.         *--argv[1] = '-';
  162.       else
  163.         argv[1] = "-l";
  164.     }
  165.       else
  166.     argv[1] = "-l";
  167.     }
  168.   while ((c = getopt_long (argc, argv, "n:lbcfqv", long_options, &longind))
  169.      != EOF)
  170.     {
  171.       if (c == 0)
  172.     c = long_options[longind].val;
  173.       switch (c)
  174.     {
  175.     case 'n':
  176.       if (*optarg == '+')
  177.         {
  178.           mode |= START;
  179.           ++optarg;
  180.         }
  181.       number = atou (optarg);
  182.       if (number == -1)
  183.         error (1, 0, "invalid number `%s'", optarg);
  184.       break;
  185.     case 'l':
  186.       mode &= ~(CHARS | BLOCKS);
  187.       break;
  188.     case 'b':
  189.       mode |= BLOCKS;
  190.       mode &= ~CHARS;
  191.       break;
  192.     case 'c':
  193.       mode |= CHARS;
  194.       mode &= ~BLOCKS;
  195.       break;
  196.     case 'f':
  197.       mode |= FOREVER;
  198.       break;
  199.     case 'q':
  200.       header_mode = never;
  201.       break;
  202.     case 'v':
  203.       header_mode = always;
  204.       break;
  205.     default:
  206.       usage ();
  207.     }
  208.     }
  209.  
  210.   if (number == -1)
  211.     number = DEFAULT_NUMBER;
  212.  
  213.   /* To start printing with item `number' from the start of the file, skip
  214.      `number' - 1 items.  `tail +0' is actually meaningless, but for Unix
  215.      compatibility it's treated the same as `tail +1'. */
  216.   if (mode & START)
  217.     {
  218.       if (number)
  219.     --number;
  220.     }
  221.  
  222.   if (mode & BLOCKS)
  223.     number *= BLOCKSIZE;
  224.  
  225.   if (optind < argc - 1 && (mode & FOREVER))
  226.     error (1, 0, "cannot follow the ends of multiple files");
  227.  
  228.   if (header_mode == always
  229.       || header_mode == multiple_files && optind < argc - 1)
  230.     mode |= HEADERS;
  231.  
  232.   if (optind == argc)
  233.     errors |= tail_file ("-", mode, number);
  234.  
  235.   for (; optind < argc; ++optind)
  236.     errors |= tail_file (argv[optind], mode, number);
  237.  
  238.   exit (errors);
  239. }
  240.  
  241. /* Display the last `number' units of file `filename', controlled by
  242.    the flags in `mode'.  "-" for `filename' means the standard input.
  243.    Return 0 if successful, 1 if an error occurred. */
  244.  
  245. int
  246. tail_file (filename, mode, number)
  247.      char *filename;
  248.      int mode;
  249.      long number;
  250. {
  251.   int fd;
  252.  
  253.   if (!strcmp (filename, "-"))
  254.     {
  255.       filename = "standard input";
  256.       if (mode & HEADERS)
  257.     write_header (filename);
  258.       return tail (filename, 0, mode, number);
  259.     }
  260.   else
  261.     {
  262.       fd = open (filename, O_RDONLY);
  263.       if (fd == -1)
  264.     {
  265.       error (0, errno, "%s", filename);
  266.       return 1;
  267.     }
  268.       else
  269.     {
  270.       int errors;
  271.  
  272.       if (mode & HEADERS)
  273.         write_header (filename);
  274.       errors = tail (filename, fd, mode, number);
  275.       close (fd);
  276.       return errors;
  277.     }
  278.     }
  279. }
  280.  
  281. void
  282. write_header (filename)
  283.      char *filename;
  284. {
  285.   static int first_file = 1;
  286.  
  287.   if (first_file)
  288.     {
  289.       xwrite (1, "==> ", 4);
  290.       first_file = 0;
  291.     }
  292.   else
  293.     xwrite (1, "\n==> ", 5);
  294.   xwrite (1, filename, strlen (filename));
  295.   xwrite (1, " <==\n", 5);
  296. }
  297.  
  298. /* Display the last `number' units of file `filename', open for reading
  299.    in `fd', controlled by `mode'.
  300.    Return 0 if successful, 1 if an error occurred. */
  301.  
  302. int
  303. tail (filename, fd, mode, number)
  304.      char *filename;
  305.      int fd;
  306.      int mode;
  307.      long number;
  308. {
  309.   if (mode & (CHARS | BLOCKS))
  310.     return tail_chars (filename, fd, mode, number);
  311.   else
  312.     return tail_lines (filename, fd, mode, number);
  313. }
  314.  
  315. /* Display the last part of file `filename', open for reading in`fd',
  316.    using `number' characters, controlled by `mode'.
  317.    Return 0 if successful, 1 if an error occurred. */
  318.  
  319. int
  320. tail_chars (filename, fd, mode, number)
  321.      char *filename;
  322.      int fd;
  323.      int mode;
  324.      long number;
  325. {
  326.   int length;
  327.  
  328.   if (mode & START)
  329.     {
  330.       if (lseek (fd, number, L_SET) < 0)
  331.     {
  332.       /* Reading from a pipe. */
  333.       mode &= ~FOREVER;
  334.       if (start_chars (filename, fd, number))
  335.         return 1;
  336.     }
  337.       dump_remainder (filename, fd, mode);
  338.     }
  339.   else
  340.     {
  341.       length = lseek (fd, 0L, L_XTND);
  342.       if (length >= 0)
  343.     {
  344.       if (length <= number)
  345.         /* The file is shorter than we want, or just the right size, so
  346.            print the whole file. */
  347.         lseek (fd, 0L, L_SET);
  348.       else
  349.         /* The file is longer than we want, so go back. */
  350.         lseek (fd, -number, L_XTND);
  351.       dump_remainder (filename, fd, mode);
  352.     }
  353.       else
  354.     return pipe_chars (filename, fd, number);
  355.     }
  356.   return 0;
  357. }
  358.  
  359. /* Display the last part of file `filename', open for reading on `fd',
  360.    using `number' lines, controlled by `mode'.
  361.    Return 0 if successful, 1 if an error occurred. */
  362.  
  363. int
  364. tail_lines (filename, fd, mode, number)
  365.      char *filename;
  366.      int fd;
  367.      int mode;
  368.      long number;
  369. {
  370.   long length;
  371.  
  372.   if (mode & START)
  373.     {
  374.       if (lseek (fd, 0L, L_SET) < 0)
  375.     mode &= ~FOREVER;
  376.       if (start_lines (filename, fd, number))
  377.     return 1;
  378.       dump_remainder (filename, fd, mode);
  379.     }
  380.   else
  381.     {
  382.       length = lseek (fd, 0L, L_XTND);
  383.       if (length >= 0)
  384.     {
  385.       if (length != 0 && file_lines (filename, fd, number, length))
  386.         return 1;
  387.       dump_remainder (filename, fd, mode);
  388.     }
  389.       else
  390.     return pipe_lines (filename, fd, number);
  391.     }
  392.   return 0;
  393. }
  394.  
  395. /* Print the last `number' lines from the end of file `fd'.
  396.    Go backward through the file, reading `BUFSIZE' bytes at a time (except
  397.    probably the first), until we hit the start of the file or have
  398.    read `number' newlines.
  399.    `pos' starts out as the length of the file (the offset of the last
  400.    byte of the file + 1).
  401.    Return 0 if successful, 1 if an error occurred. */
  402.  
  403. int
  404. file_lines (filename, fd, number, pos)
  405.      char *filename;
  406.      int fd;
  407.      long number;
  408.      long pos;
  409. {
  410.   char buffer[BUFSIZE];
  411.   int chars_read;
  412.   int i;            /* Index into `buffer' for scanning. */
  413.  
  414.   if (number == 0)
  415.     return 0;
  416.  
  417.   /* Set `chars_read' to the size of the last, probably partial, buffer;
  418.      0 < `chars_read' <= `BUFSIZE'. */
  419.   chars_read = pos % BUFSIZE;
  420.   if (chars_read == 0)
  421.     chars_read = BUFSIZE;
  422.   /* Make `pos' a multiple of `BUFSIZE' (0 if the file is short), so that all
  423.      reads will be on block boundaries, which might increase efficiency. */
  424.   pos -= chars_read;
  425.   lseek (fd, pos, L_SET);
  426.   chars_read = read (fd, buffer, chars_read);
  427.   if (chars_read == -1)
  428.     {
  429.       error (0, errno, "%s", filename);
  430.       return 1;
  431.     }
  432.  
  433.   /* Count the incomplete line on files that don't end with a newline. */
  434.   if (chars_read && buffer[chars_read - 1] != '\n')
  435.     --number;
  436.  
  437.   do
  438.     {
  439.       /* Scan backward, counting the newlines in this bufferfull. */
  440.       for (i = chars_read - 1; i >= 0; i--)
  441.     {
  442.       /* Have we counted the requested number of newlines yet? */
  443.       if (buffer[i] == '\n' && number-- == 0)
  444.         {
  445.           /* If this newline wasn't the last character in the buffer,
  446.              print the text after it. */
  447.           if (i != chars_read - 1)
  448.         xwrite (1, &buffer[i + 1], chars_read - (i + 1));
  449.           return 0;
  450.         }
  451.     }
  452.       /* Not enough newlines in that bufferfull. */
  453.       if (pos == 0)
  454.     {
  455.       /* Not enough lines in the file; print the entire file. */
  456.       lseek (fd, 0L, L_SET);
  457.       return 0;
  458.     }
  459.       pos -= BUFSIZE;
  460.       lseek (fd, pos, L_SET);
  461.     }
  462.   while ((chars_read = read (fd, buffer, BUFSIZE)) > 0);
  463.   if (chars_read == -1)
  464.     {
  465.       error (0, errno, "%s", filename);
  466.       return 1;
  467.     }
  468.   return 0;
  469. }
  470.  
  471. /* Print the last `number' lines from the end of the standard input,
  472.    open for reading as pipe `fd'.
  473.    Buffer the text as a linked list of LBUFFERs, adding them as needed.
  474.    Return 0 if successful, 1 if an error occured. */
  475.  
  476. int
  477. pipe_lines (filename, fd, number)
  478.      char *filename;
  479.      int fd;
  480.      long number;
  481. {
  482.   struct linebuffer
  483.   {
  484.     int nchars, nlines;
  485.     char buffer[BUFSIZE];
  486.     struct linebuffer *next;
  487.   };
  488.   typedef struct linebuffer LBUFFER;
  489.   LBUFFER *first, *last, *tmp;
  490.   int i;            /* Index into buffers. */
  491.   int total_lines = 0;        /* Total number of newlines in all buffers. */
  492.   int errors = 0;
  493.  
  494.   first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
  495.   first->nchars = first->nlines = 0;
  496.   tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
  497.  
  498.   /* Input is always read into a fresh buffer. */
  499.   while ((tmp->nchars = read (fd, tmp->buffer, BUFSIZE)) > 0)
  500.     {
  501.       tmp->nlines = 0;
  502.       tmp->next = NULL;
  503.  
  504.       /* Count the number of newlines just read. */
  505.       for (i = 0; i < tmp->nchars; i++)
  506.     if (tmp->buffer[i] == '\n')
  507.       ++tmp->nlines;
  508.       total_lines += tmp->nlines;
  509.  
  510.       /* If there is enough room in the last buffer read, just append the new
  511.          one to it.  This is because when reading from a pipe, `nchars' can
  512.          often be very small. */
  513.       if (tmp->nchars + last->nchars < BUFSIZE)
  514.     {
  515.       bcopy (tmp->buffer, &last->buffer[last->nchars], tmp->nchars);
  516.       last->nchars += tmp->nchars;
  517.       last->nlines += tmp->nlines;
  518.     }
  519.       else
  520.     {
  521.       /* If there's not enough room, link the new buffer onto the end of
  522.          the list, then either free up the oldest buffer for the next
  523.          read if that would leave enough lines, or else malloc a new one.
  524.          Some compaction mechanism is possible but probably not
  525.          worthwhile. */
  526.       last = last->next = tmp;
  527.       if (total_lines - first->nlines > number)
  528.         {
  529.           tmp = first;
  530.           total_lines -= first->nlines;
  531.           first = first->next;
  532.         }
  533.       else
  534.         tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
  535.     }
  536.     }
  537.   if (tmp->nchars == -1)
  538.     {
  539.       error (0, errno, "%s", filename);
  540.       errors = 1;
  541.       free ((char *) tmp);
  542.       goto free_lbuffers;
  543.     }
  544.  
  545.   free ((char *) tmp);
  546.  
  547.   /* This prevents a core dump when the pipe contains no newlines. */
  548.   if (number == 0)
  549.     goto free_lbuffers;
  550.  
  551.   /* Count the incomplete line on files that don't end with a newline. */
  552.   if (last->buffer[last->nchars - 1] != '\n')
  553.     {
  554.       ++last->nlines;
  555.       ++total_lines;
  556.     }
  557.  
  558.   /* Run through the list, printing lines.  First, skip over unneeded
  559.      buffers. */
  560.   for (tmp = first; total_lines - tmp->nlines > number; tmp = tmp->next)
  561.     total_lines -= tmp->nlines;
  562.  
  563.   /* Find the correct beginning, then print the rest of the file. */
  564.   if (total_lines > number)
  565.     {
  566.       char *cp;
  567.  
  568.       /* Skip `total_lines' - `number' newlines.  We made sure that
  569.          `total_lines' - `number' <= `tmp->nlines'. */
  570.       cp = tmp->buffer;
  571.       for (i = total_lines - number; i; --i)
  572.     while (*cp++ != '\n')
  573.       /* Do nothing. */ ;
  574.       i = cp - tmp->buffer;
  575.     }
  576.   else
  577.     i = 0;
  578.   xwrite (1, &tmp->buffer[i], tmp->nchars - i);
  579.  
  580.   for (tmp = tmp->next; tmp; tmp = tmp->next)
  581.     xwrite (1, tmp->buffer, tmp->nchars);
  582.  
  583. free_lbuffers:
  584.   while (first)
  585.     {
  586.       tmp = first->next;
  587.       free ((char *) first);
  588.       first = tmp;
  589.     }
  590.   return errors;
  591. }
  592.  
  593. /* Print the last `number' characters from the end of pipe `fd'.
  594.    This is a stripped down version of pipe_lines.
  595.    Return 0 if successful, 1 if an error occurred. */
  596.  
  597. int
  598. pipe_chars (filename, fd, number)
  599.      char *filename;
  600.      int fd;
  601.      long number;
  602. {
  603.   struct charbuffer
  604.   {
  605.     int nchars;
  606.     char buffer[BUFSIZE];
  607.     struct charbuffer *next;
  608.   };
  609.   typedef struct charbuffer CBUFFER;
  610.   CBUFFER *first, *last, *tmp;
  611.   int i;            /* Index into buffers. */
  612.   int total_chars = 0;        /* Total characters in all buffers. */
  613.   int errors = 0;
  614.  
  615.   first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
  616.   first->nchars = 0;
  617.   tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
  618.  
  619.   /* Input is always read into a fresh buffer. */
  620.   while ((tmp->nchars = read (fd, tmp->buffer, BUFSIZE)) > 0)
  621.     {
  622.       tmp->next = NULL;
  623.  
  624.       total_chars += tmp->nchars;
  625.       /* If there is enough room in the last buffer read, just append the new
  626.          one to it.  This is because when reading from a pipe, `nchars' can
  627.          often be very small. */
  628.       if (tmp->nchars + last->nchars < BUFSIZE)
  629.     {
  630.       bcopy (tmp->buffer, &last->buffer[last->nchars], tmp->nchars);
  631.       last->nchars += tmp->nchars;
  632.     }
  633.       else
  634.     {
  635.       /* If there's not enough room, link the new buffer onto the end of
  636.          the list, then either free up the oldest buffer for the next
  637.          read if that would leave enough characters, or else malloc a new
  638.          one.  Some compaction mechanism is possible but probably not
  639.          worthwhile. */
  640.       last = last->next = tmp;
  641.       if (total_chars - first->nchars > number)
  642.         {
  643.           tmp = first;
  644.           total_chars -= first->nchars;
  645.           first = first->next;
  646.         }
  647.       else
  648.         {
  649.           tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
  650.         }
  651.     }
  652.     }
  653.   if (tmp->nchars == -1)
  654.     {
  655.       error (0, errno, "%s", filename);
  656.       errors = 1;
  657.       free ((char *) tmp);
  658.       goto free_cbuffers;
  659.     }
  660.  
  661.   free ((char *) tmp);
  662.  
  663.   /* Run through the list, printing characters.  First, skip over unneeded
  664.      buffers. */
  665.   for (tmp = first; total_chars - tmp->nchars > number; tmp = tmp->next)
  666.     total_chars -= tmp->nchars;
  667.  
  668.   /* Find the correct beginning, then print the rest of the file.
  669.      We made sure that `total_chars' - `number' <= `tmp->nchars'. */
  670.   if (total_chars > number)
  671.     i = total_chars - number;
  672.   else
  673.     i = 0;
  674.   xwrite (1, &tmp->buffer[i], tmp->nchars - i);
  675.  
  676.   for (tmp = tmp->next; tmp; tmp = tmp->next)
  677.     xwrite (1, tmp->buffer, tmp->nchars);
  678.  
  679. free_cbuffers:
  680.   while (first)
  681.     {
  682.       tmp = first->next;
  683.       free ((char *) first);
  684.       first = tmp;
  685.     }
  686.   return errors;
  687. }
  688.  
  689. /* Skip `number' characters from the start of pipe `fd', and print
  690.    any extra characters that were read beyond that.
  691.    Return 1 on error, 0 if ok.  */
  692.  
  693. int
  694. start_chars (filename, fd, number)
  695.      char *filename;
  696.      int fd;
  697.      long number;
  698. {
  699.   char buffer[BUFSIZE];
  700.   int chars_read = 0;
  701.  
  702.   while (number > 0 && (chars_read = read (fd, buffer, BUFSIZE)) > 0)
  703.     number -= chars_read;
  704.   if (chars_read == -1)
  705.     {
  706.       error (0, errno, "%s", filename);
  707.       return 1;
  708.     }
  709.   else if (number < 0)
  710.     xwrite (1, &buffer[chars_read + number], -number);
  711.   return 0;
  712. }
  713.  
  714. /* Skip `number' lines at the start of file or pipe `fd', and print
  715.    any extra characters that were read beyond that.
  716.    Return 1 on error, 0 if ok.  */
  717.  
  718. int
  719. start_lines (filename, fd, number)
  720.      char *filename;
  721.      int fd;
  722.      long number;
  723. {
  724.   char buffer[BUFSIZE];
  725.   int chars_read = 0;
  726.   int chars_to_skip = 0;
  727.  
  728.   while (number && (chars_read = read (fd, buffer, BUFSIZE)) > 0)
  729.     {
  730.       chars_to_skip = 0;
  731.       while (chars_to_skip < chars_read)
  732.     if (buffer[chars_to_skip++] == '\n' && --number == 0)
  733.       break;
  734.     }
  735.   if (chars_read == -1)
  736.     {
  737.       error (0, errno, "%s", filename);
  738.       return 1;
  739.     }
  740.   else if (chars_to_skip < chars_read)
  741.     xwrite (1, &buffer[chars_to_skip], chars_read - chars_to_skip);
  742.   return 0;
  743. }
  744.  
  745. /* Display file `filename' from the current position in `fd'
  746.    to the end.  If selected in `mode', keep reading from the
  747.    end of the file until killed. */
  748.  
  749. void
  750. dump_remainder (filename, fd, mode)
  751.      char *filename;
  752.      int fd;
  753.      int mode;
  754. {
  755.   char buffer[BUFSIZE];
  756.   int chars_read;
  757.  
  758. output:
  759.   while ((chars_read = read (fd, buffer, BUFSIZE)) > 0)
  760.     xwrite (1, buffer, chars_read);
  761.   if (chars_read == -1)
  762.     error (1, errno, "%s", filename);
  763.   if (mode & FOREVER)
  764.     {
  765.       sleep (1);
  766.       goto output;
  767.     }
  768. }
  769.  
  770. /* Write plus error check. */
  771.  
  772. void
  773. xwrite (fd, buffer, count)
  774.      int fd;
  775.      int count;
  776.      char *buffer;
  777. {
  778.   fd = write (fd, buffer, count);
  779.   if (fd != count)
  780.     error (1, errno, "write error");
  781. }
  782.  
  783. /* Allocate `size' bytes of memory dynamically, with error check. */
  784.  
  785. char *
  786. xmalloc (size)
  787.      int size;
  788. {
  789.   char *p;
  790.  
  791.   p = malloc ((unsigned) size);
  792.   if (p == NULL)
  793.     error (1, 0, "virtual memory exhausted");
  794.   return p;
  795. }
  796.  
  797. /* Convert `str', a string of ASCII digits, into an unsigned integer.
  798.    Return -1 if `str' does not represent a valid unsigned integer. */
  799.  
  800. long
  801. atou (str)
  802.      char *str;
  803. {
  804.   unsigned long value;
  805.  
  806.   for (value = 0; ISDIGIT (*str); ++str)
  807.     value = value * 10 + *str - '0';
  808.   return *str ? -1 : value;
  809. }
  810.  
  811. void
  812. usage ()
  813. {
  814.   fprintf (stderr, "\
  815. Usage: %s [-n [+]#] [-lbcfqv] [+number [+]#] [+lines] [+blocks]\n\
  816.        [+chars] [+follow] [+quiet] [+silent] [+verbose] [file...]\n\
  817. \n\
  818.        %s [+/-#lbcfqv] [file...]\n", program_name, program_name);
  819.   exit (1);
  820. }
  821.